<template>
  <div class="dashboard-container">
    <!-- 头部控制面板 -->
    <div class="control-panel">
      <div class="panel-left">
        <h2>📊 实时数据监控系统</h2>
        <p class="subtitle">高级 Vuex 特性演示：插件、性能优化、复杂异步数据流</p>
      </div>
      
      <div class="panel-right">
        <div class="connection-status">
          <span class="status-dot" :class="connectionInfo.color"></span>
          {{ connectionInfo.text }}
        </div>
        
        <button 
          @click="toggleDataStream" 
          :disabled="connectionStatus === 'connecting'"
          :class="['stream-btn', isStreaming ? 'stop' : 'start']"
        >
          {{ isStreaming ? '⏹️ 停止监控' : '▶️ 开始监控' }}
        </button>
      </div>
    </div>

    <!-- 实时指标仪表板 -->
    <div class="metrics-dashboard">
      <div class="metric-card" v-for="(value, key) in metrics" :key="key">
        <div class="metric-header">
          <span class="metric-icon">{{ getMetricIcon(key) }}</span>
          <span class="metric-name">{{ getMetricName(key) }}</span>
        </div>
        
        <div class="metric-value">
          {{ formatMetricValue(key, value) }}
        </div>
        
        <div class="metric-progress">
          <div 
            class="progress-bar" 
            :style="{ 
              width: getProgressWidth(key, value),
              backgroundColor: getProgressColor(key, value)
            }"
          ></div>
        </div>
        
        <div class="metric-status" :class="getMetricStatus(key, value)">
          {{ getStatusText(key, value) }}
        </div>
      </div>
    </div>

    <!-- 系统状态概览 -->
    <div class="system-overview">
      <div class="status-card">
        <h3>🎯 系统状态</h3>
        <div class="status-indicator" :class="systemStatus.overall">
          {{ systemStatus.overall === 'healthy' ? '健康' : '警告' }}
        </div>
        <div class="status-details">
          <div v-for="(status, component) in systemStatus.details" :key="component">
            <span>{{ getComponentName(component) }}: </span>
            <span :class="status">{{ status === 'normal' ? '正常' : '高负载' }}</span>
          </div>
        </div>
      </div>
      
      <div class="stats-card">
        <h3>📈 数据统计</h3>
        <div v-if="dataStats" class="stats-grid">
          <div v-for="(stat, key) in dataStats" :key="key" class="stat-item">
            <div class="stat-label">{{ getMetricName(key) }}</div>
            <div class="stat-values">
              <span>最小: {{ stat.min }}</span>
              <span>最大: {{ stat.max }}</span>
              <span>平均: {{ stat.avg }}</span>
            </div>
          </div>
        </div>
        <div v-else class="no-data">暂无统计数据</div>
      </div>
      
      <div class="error-card">
        <h3>⚠️ 错误监控</h3>
        <div class="error-summary">
          <div>总错误: {{ errorSummary.total }}</div>
          <div>最近1小时: {{ errorSummary.recent }}</div>
        </div>
        <div v-if="errors.length > 0" class="recent-errors">
          <div v-for="error in errors.slice(-3)" :key="error.id" class="error-item">
            <span class="error-type">{{ error.type }}</span>
            <span class="error-message">{{ error.message }}</span>
            <span class="error-time">{{ formatTime(error.timestamp) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据过滤和导出 -->
    <div class="data-controls">
      <div class="filter-section">
        <h3>🔍 数据过滤</h3>
        <div class="filter-controls">
          <select v-model="localFilters.dateRange" @change="applyFilters">
            <option value="today">今天</option>
            <option value="week">最近一周</option>
            <option value="all">全部</option>
          </select>
          
          <select v-model="localFilters.metricType" @change="applyFilters">
            <option value="all">所有指标</option>
            <option value="cpu">CPU</option>
            <option value="memory">内存</option>
            <option value="network">网络</option>
          </select>
          
          <button @click="clearHistory" class="clear-btn">清空历史</button>
        </div>
      </div>
      
      <div class="export-section">
        <h3>📤 数据导出</h3>
        <div class="export-controls">
          <button 
            @click="exportData('json')" 
            :disabled="exportStatus === 'pending'"
            class="export-btn"
          >
            {{ exportStatus === 'pending' ? '导出中...' : '导出 JSON' }}
          </button>
          
          <button 
            @click="exportData('csv')" 
            :disabled="exportStatus === 'pending'"
            class="export-btn"
          >
            导出 CSV
          </button>
        </div>
      </div>
    </div>

    <!-- 历史数据图表（简化版） -->
    <div class="chart-section">
      <h3>📊 历史趋势</h3>
      <div class="chart-container">
        <div v-if="filteredHistory.length > 0" class="simple-chart">
          <div class="chart-legend">
            <span v-for="metric in ['cpu', 'memory']" :key="metric" class="legend-item">
              <span class="legend-color" :style="{ backgroundColor: getChartColor(metric) }"></span>
              {{ getMetricName(metric) }}
            </span>
          </div>
          
          <div class="chart-data">
            <div 
              v-for="(record, index) in filteredHistory.slice(-20)" 
              :key="index"
              class="data-point"
              :title="`${formatTime(record.timestamp)} - CPU: ${record.data.cpu}%, Memory: ${record.data.memory}%`"
            >
              <div 
                class="bar cpu" 
                :style="{ 
                  height: `${record.data.cpu}%`,
                  backgroundColor: getChartColor('cpu')
                }"
              ></div>
              <div 
                class="bar memory" 
                :style="{ 
                  height: `${record.data.memory}%`,
                  backgroundColor: getChartColor('memory')
                }"
              ></div>
            </div>
          </div>
        </div>
        <div v-else class="no-chart-data">
          暂无历史数据，请开始数据监控
        </div>
      </div>
    </div>

    <!-- 性能监控信息 -->
    <div class="performance-section" v-if="$store.getPerformanceStats">
      <h3>⚡ 性能监控</h3>
      <div class="performance-stats">
        <div class="perf-item">
          <span>总操作数: {{ performanceStats.totalOperations }}</span>
        </div>
        <div class="perf-item">
          <span>平均耗时: {{ performanceStats.averageTime.toFixed(2) }}ms</span>
        </div>
        <div class="perf-item">
          <span>慢操作: {{ performanceStats.slowOperations }}</span>
        </div>
        <button @click="clearPerformanceRecords" class="clear-perf-btn">
          清除记录
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
  name: 'DashboardExample',
  data() {
    return {
      localFilters: {
        dateRange: 'today',
        metricType: 'all'
      },
      performanceStats: {
        totalOperations: 0,
        averageTime: 0,
        slowOperations: 0
      }
    }
  },
  
  computed: {
    ...mapState('dashboard', [
      'metrics',
      'history', 
      'filters',
      'isStreaming',
      'connectionStatus',
      'errors',
      'exportStatus'
    ]),
    
    ...mapGetters('dashboard', [
      'filteredHistory',
      'systemStatus',
      'connectionInfo',
      'dataStats',
      'errorSummary'
    ])
  },
  
  mounted() {
    // 获取性能统计
    this.updatePerformanceStats()
    
    // 定期更新性能统计
    this.performanceInterval = setInterval(() => {
      this.updatePerformanceStats()
    }, 5000)
  },
  
  beforeDestroy() {
    // 停止数据流
    if (this.isStreaming) {
      this.stopDataStream()
    }
    
    // 清除定时器
    if (this.performanceInterval) {
      clearInterval(this.performanceInterval)
    }
  },
  
  methods: {
    ...mapActions('dashboard', [
      'startDataStream',
      'stopDataStream',
      'applyFilters',
      'exportData',
      'clearErrors'
    ]),
    
    async toggleDataStream() {
      if (this.isStreaming) {
        await this.stopDataStream()
      } else {
        const result = await this.startDataStream()
        if (result.success) {
          this.$message?.success?.(result.message)
        } else {
          this.$message?.error?.(result.message)
        }
      }
    },
    
    applyFilters() {
      this.$store.dispatch('dashboard/applyFilters', this.localFilters)
    },
    
    async exportData(format) {
      const result = await this.$store.dispatch('dashboard/exportData', format)
      if (result.success) {
        this.$message?.success?.(`数据导出成功 (${format})`)
      } else {
        this.$message?.error?.(result.message)
      }
    },
    
    clearHistory() {
      this.$store.commit('dashboard/CLEAR_HISTORY')
      this.$message?.success?.('历史数据已清空')
    },
    
    clearPerformanceRecords() {
      if (this.$store.clearPerformanceRecords) {
        this.$store.clearPerformanceRecords()
        this.updatePerformanceStats()
        this.$message?.success?.('性能记录已清除')
      }
    },
    
    updatePerformanceStats() {
      if (this.$store.getPerformanceStats) {
        this.performanceStats = this.$store.getPerformanceStats()
      }
    },
    
    // 工具方法
    getMetricIcon(key) {
      const icons = {
        cpu: '🔥',
        memory: '💾',
        network: '📡',
        activeUsers: '👥',
        requests: '📨'
      }
      return icons[key] || '📊'
    },
    
    getMetricName(key) {
      const names = {
        cpu: 'CPU使用率',
        memory: '内存使用率',
        network: '网络流量',
        activeUsers: '活跃用户',
        requests: '请求数量'
      }
      return names[key] || key
    },
    
    formatMetricValue(key, value) {
      if (['cpu', 'memory'].includes(key)) {
        return `${value}%`
      }
      if (key === 'network') {
        return `${value}MB/s`
      }
      return value.toLocaleString()
    },
    
    getProgressWidth(key, value) {
      if (['cpu', 'memory'].includes(key)) {
        return `${Math.min(value, 100)}%`
      }
      if (key === 'network') {
        return `${Math.min(value / 10, 100)}%`
      }
      return '50%'
    },
    
    getProgressColor(key, value) {
      if (['cpu', 'memory'].includes(key)) {
        return value > 80 ? '#f56565' : value > 60 ? '#ed8936' : '#48bb78'
      }
      return '#4299e1'
    },
    
    getMetricStatus(key, value) {
      if (['cpu', 'memory'].includes(key)) {
        return value > 80 ? 'critical' : value > 60 ? 'warning' : 'normal'
      }
      return 'normal'
    },
    
    getStatusText(key, value) {
      if (['cpu', 'memory'].includes(key)) {
        return value > 80 ? '高负载' : value > 60 ? '中等负载' : '正常'
      }
      return '正常'
    },
    
    getComponentName(component) {
      const names = {
        cpu: 'CPU',
        memory: '内存',
        network: '网络'
      }
      return names[component] || component
    },
    
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString()
    },
    
    getChartColor(metric) {
      const colors = {
        cpu: '#f56565',
        memory: '#4299e1',
        network: '#48bb78'
      }
      return colors[metric] || '#a0aec0'
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  color: #2d3748;
}

.control-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  backdrop-filter: blur(10px);
}

.panel-left h2 {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-size: 1.5rem;
}

.subtitle {
  margin: 0;
  color: #718096;
  font-size: 0.9rem;
}

.panel-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f7fafc;
  border-radius: 20px;
  font-size: 0.9rem;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-dot.success { background: #48bb78; }
.status-dot.warning { background: #ed8936; }
.status-dot.info { background: #4299e1; }
.status-dot.error { background: #f56565; }

.stream-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 25px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.stream-btn.start {
  background: #48bb78;
  color: white;
}

.stream-btn.stop {
  background: #f56565;
  color: white;
}

.stream-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stream-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.metrics-dashboard {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.metric-card {
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  transition: transform 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-3px);
}

.metric-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
}

.metric-icon {
  font-size: 1.2rem;
}

.metric-name {
  font-weight: 500;
  color: #4a5568;
}

.metric-value {
  font-size: 2rem;
  font-weight: bold;
  color: #2d3748;
  margin-bottom: 10px;
}

.metric-progress {
  height: 6px;
  background: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-bar {
  height: 100%;
  transition: width 0.3s ease;
  border-radius: 3px;
}

.metric-status {
  font-size: 0.8rem;
  font-weight: 500;
  text-align: center;
  padding: 4px 8px;
  border-radius: 12px;
}

.metric-status.normal {
  background: #c6f6d5;
  color: #22543d;
}

.metric-status.warning {
  background: #feebc8;
  color: #c05621;
}

.metric-status.critical {
  background: #fed7d7;
  color: #c53030;
}

.system-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.status-card,
.stats-card,
.error-card {
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.status-card h3,
.stats-card h3,
.error-card h3 {
  margin: 0 0 15px 0;
  color: #2d3748;
  font-size: 1.1rem;
}

.status-indicator {
  padding: 8px 16px;
  border-radius: 20px;
  text-align: center;
  font-weight: 500;
  margin-bottom: 15px;
}

.status-indicator.healthy {
  background: #c6f6d5;
  color: #22543d;
}

.status-indicator.warning {
  background: #feebc8;
  color: #c05621;
}

.status-details div {
  margin-bottom: 5px;
  font-size: 0.9rem;
}

.status-details .normal {
  color: #22543d;
}

.status-details .high {
  color: #c53030;
}

.stats-grid {
  display: grid;
  gap: 10px;
}

.stat-item {
  padding: 10px;
  background: #f7fafc;
  border-radius: 8px;
}

.stat-label {
  font-weight: 500;
  margin-bottom: 5px;
  color: #4a5568;
}

.stat-values {
  display: flex;
  gap: 10px;
  font-size: 0.8rem;
  color: #718096;
}

.error-summary {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  font-size: 0.9rem;
}

.recent-errors {
  max-height: 120px;
  overflow-y: auto;
}

.error-item {
  display: flex;
  gap: 10px;
  padding: 5px;
  font-size: 0.8rem;
  border-bottom: 1px solid #e2e8f0;
}

.error-type {
  font-weight: 500;
  color: #f56565;
}

.error-message {
  flex: 1;
  color: #4a5568;
}

.error-time {
  color: #a0aec0;
}

.data-controls {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.filter-section,
.export-section {
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.filter-section h3,
.export-section h3 {
  margin: 0 0 15px 0;
  color: #2d3748;
}

.filter-controls,
.export-controls {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-controls select,
.clear-btn,
.export-btn {
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
}

.export-btn {
  background: #4299e1;
  color: white;
  border-color: #4299e1;
}

.export-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.clear-btn {
  background: #f56565;
  color: white;
  border-color: #f56565;
}

.chart-section,
.performance-section {
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  margin-bottom: 20px;
}

.chart-section h3,
.performance-section h3 {
  margin: 0 0 15px 0;
  color: #2d3748;
}

.chart-legend {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.chart-data {
  display: flex;
  gap: 2px;
  height: 200px;
  align-items: flex-end;
  padding: 10px;
  background: #f7fafc;
  border-radius: 8px;
}

.data-point {
  display: flex;
  gap: 1px;
  align-items: flex-end;
  flex: 1;
  min-width: 8px;
}

.bar {
  flex: 1;
  min-height: 2px;
  border-radius: 2px 2px 0 0;
  transition: height 0.3s ease;
}

.no-chart-data,
.no-data {
  text-align: center;
  color: #a0aec0;
  padding: 40px;
  font-style: italic;
}

.performance-stats {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.perf-item {
  background: #f7fafc;
  padding: 10px 15px;
  border-radius: 8px;
  font-size: 0.9rem;
}

.clear-perf-btn {
  padding: 8px 12px;
  background: #ed8936;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .control-panel {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .metrics-dashboard {
    grid-template-columns: 1fr;
  }
  
  .data-controls {
    grid-template-columns: 1fr;
  }
  
  .performance-stats {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>